/**
 * 父子进程共同协同实现ls wc-l
 * @author: sundx
 * @date: 2020-05-30 22:01:33
 * @Last Modified by: sundx
 * @Last Modified time: 2020-05-30 22:03:19
 */
#include <iostream>
#include <unistd.h>
void outError(int, const char *);
int main() {
  int fd[2];
  int ret;
  pid_t pid;
  ret = pipe(fd);
  outError(ret, "pipe error");
  pid = fork();
  if (pid > 0) { //父进程 实现ls
    ret = close(fd[0]);
    outError(ret, "father close fd[0] error");
    ret = dup2(fd[1], STDOUT_FILENO);
    outError(ret, "father dup2  error");
    execlp("ls", "ls", NULL);
    std::cout << "ls error" << std::endl;
  } else if (pid == 0) { //子进程 实现wc -l
    ret = close(fd[1]);
    outError(ret, "son close fd[0] error");
    ret = dup2(fd[0], STDIN_FILENO);
    outError(ret, "son dup2  error");
    execlp("wc", "wc", "-l", NULL);
    std::cout << "wc -l error" << std::endl;
  } else {
    outError(pid, "fork failed");
  }
}
void outError(int a, const char *errorMessage) {
  if (a == -1) {
    std::cout << errorMessage << std::endl;
    exit(EXIT_FAILURE);
  }
}